//
//  CXRefreshControl.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/24.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit

private let CXRefreshKitH: CGFloat = 50
//private let CXRefreshKitMsg:
/// 自定义下拉刷新控件
class CXRefreshControl: UIControl {
    
    /// 记录父控件
    var superV: UIScrollView?
    /// 弹出显示的刷新信息
    var deltaInfo: Int = 0
    /// 记录所处状态
    var freshState: CXRefrashState = .Normal {
        
        didSet {
            switch freshState {
            case .Pulling:
                UIView.animateWithDuration(1, animations: { () -> Void in
                    self.iconView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                self.msgView.text = "放手就起飞"
                print("放手就开始刷新")
            case .Normal:
                iconView.hidden = false
                indiView.stopAnimating()
                
                UIView.animateWithDuration(1, animations: { () -> Void in
                    self.iconView.transform = CGAffineTransformIdentity
                })
                //只有在从刷新状态切换过来时 才减少contentInset。否则一开始就会减少
                if oldValue == .Refreshing {
                    //减轻松手后superView的bounces与contengInset变化带来的冲突问题
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        UIView.animateWithDuration(0.25, animations: { () -> Void in
                            self.superV?.contentInset.top = self.superV!.contentInset.top - self.frame.height
                            self.superV?.setContentOffset(CGPoint(x: 0, y: -self.superV!.contentInset.top), animated: false)  //contentInset.top = 64
                            }, completion: { (_) -> Void in
                                //模拟新浪微博的刷新结束后弹出显示刷新信息的视图 然后视图收回
//                                self.iconView.hidden = true
//                                self.msgView.text = "新增了\(self.deltaInfo)条微博"
//                                UIView.animateWithDuration(0.5, delay: 0.25, options: [], animations: { () -> Void in
//                                    self.transform = CGAffineTransformMakeTranslation(0, CXRefreshKitH)
//                                    }, completion: { (_) -> Void in
//                                        UIView.animateWithDuration(0.5, delay: 1, options: [], animations: { () -> Void in
//                                            self.transform = CGAffineTransformIdentity
//                                            }, completion: { (_) -> Void in
//                                                self.iconView.hidden = false
//                                                self.msgView.text = "下拉来加载更多"
//                                        })
//                                })
                        })
                    })
                }
                self.msgView.text = "下拉加载更多"
                print("下拉来加载更多")
            case .Refreshing:
                print("刷新啦")
                //TODO: 添加刷新动作
                iconView.hidden = true
                indiView.startAnimating()
                //让superV悬停
        
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.superV!.contentInset.top += self.frame.height
                })
                
                sendActionsForControlEvents(.ValueChanged)   //告诉action-target
            }
        }
    }
    //初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //懒加载控件
    private lazy var iconView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var msgView: UILabel = {
        let label = UILabel(textColor: UIColor.darkGrayColor(), font: 14)
        label.text = "下拉刷新更多"
        return label
    }()
    //菊花
    private lazy var indiView: UIActivityIndicatorView = {
        let indiv = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
        return indiv
    }()
    //销毁时注销观察者身份
    deinit {
        superV?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
}
extension CXRefreshControl {
    
    func endAnimation() {
        freshState = .Normal
    }
    private func setupUI() {
        
        backgroundColor = UIColor.greenColor()
        frame = CGRect(x: 0, y: -CXRefreshKitH, width: SCREENW, height: CXRefreshKitH)
        
        addSubview(iconView)
        addSubview(msgView)
        addSubview(indiView)
        //约束
        iconView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-24)
            make.centerY.equalTo(self)
        }
        msgView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(iconView.snp_trailing)
            make.centerY.equalTo(iconView)
        }
        indiView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(iconView)
        }
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        //别忘了调用父类方法
        super.willMoveToSuperview(newSuperview)
        
        guard let scrollV = newSuperview as? UIScrollView else {
            return //不是可以滚动的视图就直接返回
        }
        
        superV = scrollV
        //拿到父控件以后 添加 KVO
        superV?.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
    }
    
    // KVO 的监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let superV = object as? UIScrollView
        //父控件滚动的 y 偏移量
        let offsetY = superV!.contentOffset.y
        //父控件的内边距 top
        let insetTop = superV!.contentInset.top
        
        //根据所处的状态 修改下拉控件的状态
        if superV!.dragging {
            
            let bound = -(insetTop + CXRefreshKitH)
            //还没有拉全
            if offsetY > bound {
                
                if freshState == .Pulling {
                    freshState = .Normal
                }
            } else {
                //已经完全显示出来
                if freshState == .Normal {
                    freshState = .Pulling
                }
            }
        } else {
            //拖拽下手已经松开；则开始加载数据刷新，给父类target发送.ValueChange消息
            if freshState == .Pulling {
                //无法从默认转改直接变成正在刷新的状态
                freshState = .Refreshing
                
            }
        }
    }
}
///  下拉状态
///
///  - Normal:     默认
///  - Pulling:    正在拖着控件
///  - Refreshing: 松手正在刷新
enum CXRefrashState: Int {
    case Normal = 0
    case Pulling = 1
    case Refreshing = 2
}